<template>
    <div ref="chartRef" :style="{ width: '100%', height: chartHeight }"></div>
  </template>
  
  <script setup lang="ts">
  // 引入 echarts 核心模块，核心模块提供了 echarts 使用必须要的接口。
  import * as echarts from "echarts/core";
  // 引入饼图图表，图表后缀都为 Chart
  import { PieChart } from "echarts/charts";
  // 引入标题，提示框，图例，数据集，内置数据转换器组件，组件后缀都为 Component
  import {
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    DatasetComponent,
    TransformComponent,
  } from "echarts/components";
  // 标签自动布局、全局过渡动画等特性
  import { LabelLayout, UniversalTransition } from "echarts/features";
  // 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
  import { CanvasRenderer } from "echarts/renderers";
  import { onMounted, onUnmounted, ref, watch, defineProps, withDefaults } from "vue";
  
  // 定义组件接收的属性
  interface Props {
    chartHeight?: string;
    data?: any;
    title?: string;
    showTitle?: boolean;
    themeColors?: string[];
    centerPosition?: [string, string];
    secondPieData?: any;
  }
  
  const props = withDefaults(defineProps<Props>(), {
    chartHeight: '300px',
    title: '数据统计',
    showTitle: false,
    themeColors: () => ['#2B5AED', '#36CBCB', '#4ECB73', '#FAD337', '#F2637B'],
    centerPosition: () => ['50%', '50%'],
  });
  
  // 注册必须的组件
  echarts.use([
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    DatasetComponent,
    TransformComponent,
    PieChart,
    LabelLayout,
    UniversalTransition,
    CanvasRenderer,
  ]);
  
  const chartRef = ref<HTMLElement | null>(null);
  let myChart: echarts.ECharts | null = null;
  
  // 初始化图表
  const initChart = () => {
    if (chartRef.value) {
      myChart = echarts.init(chartRef.value);
      updateChart();
    }
  };
  
  // 处理饼图数据
  const processPieData = (rawData: any) => {
    // 默认数据
    const defaultData = [
      { name: '类别1', value: 25 },
      { name: '类别2', value: 20 },
      { name: '类别3', value: 15 },
      { name: '类别4', value: 30 },
      { name: '类别5', value: 10 }
    ];
    
    if (!rawData) return defaultData;
    
    // 处理 survey 数据格式 (data.website 数组)
    if (rawData.data && rawData.data.website && Array.isArray(rawData.data.website)) {
      return rawData.data.website.map((item: any) => ({
        name: item.name,
        value: item.value,
        key: item.key // 保留key以便后续使用
      }));
    }
    
    // 如果数据已经是饼图所需的格式 [{name, value}]
    if (Array.isArray(rawData) && rawData.length > 0 && 'name' in rawData[0] && 'value' in rawData[0]) {
      return rawData;
    }
    
    // 如果是 website 数组本身
    if (Array.isArray(rawData) && rawData.length > 0 && 'name' in rawData[0] && 'key' in rawData[0]) {
      return rawData.map((item: any) => ({
        name: item.name,
        value: item.value,
        key: item.key
      }));
    }
    
    // 如果数据是数组且包含特定属性（匹配mock数据格式）
    if (Array.isArray(rawData) && rawData.length > 0) {
      if ('date' in rawData[0] && 'count' in rawData[0]) {
        // 将date作为name，count作为value
        return rawData.map((item: any) => ({
          name: item.date,
          value: item.count
        }));
      }
      
      // 如果是对象数组，尝试提取第一个和第二个属性作为name和value
      if (typeof rawData[0] === 'object') {
        const keys = Object.keys(rawData[0]);
        if (keys.length >= 2) {
          return rawData.map((item: any) => ({
            name: item[keys[0]],
            value: item[keys[1]]
          }));
        }
      }
    }
    
    // 如果是简单对象，转换为数组
    if (typeof rawData === 'object' && !Array.isArray(rawData)) {
      return Object.entries(rawData).map(([key, value]) => ({
        name: key,
        value: value
      }));
    }
    
    console.warn('无法识别的数据格式，使用默认数据');
    return defaultData;
  };
  
  // 更新图表数据
  const updateChart = () => {
    if (!myChart) return;
    
    const pieData = processPieData(props.data);
    
    const option: any = {
      title: {
        text: props.title,
        left: 'center',
        show: props.showTitle,
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
        backgroundColor: 'rgba(255, 255, 255, 0.8)',
        borderColor: '#F2F3F5',
        borderWidth: 1,
        textStyle: {
          color: '#333'
        }
      },
      legend: {
        orient: 'horizontal',
        bottom: '5%',
        icon: 'circle',
        itemWidth: 10,
        itemHeight: 10,
        textStyle: {
          color: '#86909C'
        }
      },
      series: [
        {
          name: props.title,
          type: 'pie',
          radius: ['40%', '55%'],
          center: props.centerPosition,
          avoidLabelOverlap: true,
          itemStyle: {
            borderRadius: 4,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 14,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: pieData,
          color: props.themeColors
        }
      ],
      animation: true
    };
    
    myChart.setOption(option);
  };
  
  // 处理窗口大小变化
  const handleResize = () => {
    myChart?.resize();
  };
  
  // 监听数据变化
  watch(() => [props.data, props.secondPieData], () => {
    updateChart();
  }, { deep: true });
  
  // 监听主题色变化
  watch(() => props.themeColors, () => {
    updateChart();
  }, { deep: true });
  
  onMounted(() => {
    initChart();
    window.addEventListener('resize', handleResize);
  });
  
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    myChart?.dispose();
  });
  </script>
  
  <style scoped lang="less">
  .chart-container {
    position: relative;
    overflow: hidden;
    border-radius: 4px;
    transition: all 0.3s;
  }
  </style>